/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package view.GUI;

import dao.Cliente.ClienteDao;
import dao.Cliente.ClienteDaoImpl;
import dao.Item.ItemDao;
import dao.NotaFiscal.NotaFiscalDao;
import dao.Pedido.PedidoDao;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.JDesktopPane;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import pojo.Cliente;
import pojo.Item;
import pojo.NotaFiscal;
import pojo.Pedido;

/**
 *
 * @author lg
 */
public class GUIVendas extends javax.swing.JInternalFrame {

    ItemDao itens;
    ClienteDao clientes;
    JDesktopPane painelPrincipal;
    PedidoDao pedidos;
    Cliente cliente;
    Pedido pedido;
    NotaFiscal notaFiscal;
    NotaFiscalDao notasFiscais;

    /**
     * Creates new form GUIVendas
     *
     * @param itens
     * @param clientes
     */
    public GUIVendas(ItemDao itens, ClienteDao clientes,
            PedidoDao pedidos, JDesktopPane painelPrincipal,
            NotaFiscalDao notasFiscais) {
        this.itens = itens;
        this.pedidos = pedidos;
        this.painelPrincipal = painelPrincipal;
        this.clientes = clientes;
        this.notasFiscais = notasFiscais;
        initComponents();
    }
    
    public GUIVendas(ItemDao itens, ClienteDao clientes,
            PedidoDao pedidos, JDesktopPane painelPrincipal,
            NotaFiscalDao notasFiscais,Pedido pedido) {
        this.itens = itens;
        this.pedidos = pedidos;
        this.painelPrincipal = painelPrincipal;
        this.clientes = clientes;
        this.notasFiscais = notasFiscais;
        this.pedido = pedido;
        initComponents();
        DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
        for (Item iten : pedido.getItens()) {
            dtm.addRow(new Object[] {iten.getNome(),iten.getQuantidade()});
        }
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        fieldNomeCliente = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        labelCPF = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(600, 450));

        jLabel1.setText("Cliente ");

        fieldNomeCliente.setEditable(false);
        fieldNomeCliente.setText("Escolha uma das opções ao lado");

        jButton1.setText("...");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Novo");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nome", "Quantidade"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.getTableHeader().setReorderingAllowed(false);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jButton3.setText("+");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("-");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("Fechar pedido");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jButton6.setText("Salvar pedido");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jButton7.setText("Cancelar");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });

        jLabel2.setText("Cpf : ");

        labelCPF.setText("null");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButton7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton6))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 511, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(fieldNomeCliente)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelCPF)
                        .addGap(0, 0, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(fieldNomeCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(labelCPF))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton4)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton5)
                    .addComponent(jButton6)
                    .addComponent(jButton7))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
        int opcao = JOptionPane.showConfirmDialog(this, "Are you sure?");
        if (opcao == 0) {
            this.dispose();
        }

    }//GEN-LAST:event_jButton7ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        GUICadastroCliente cadastroCliente = new GUICadastroCliente(
                (ClienteDaoImpl) clientes, fieldNomeCliente);
        cadastroCliente.setTitle("Escolha o cliente");
        cadastroCliente.setVisible(true);
        cadastroCliente.setResizable(true);
        cadastroCliente.setMaximizable(true);
        cadastroCliente.setClosable(true);
        cadastroCliente.setIconifiable(true);
        cadastroCliente.setVisible(true);
        cadastroCliente.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        this.painelPrincipal.add(cadastroCliente);
        cadastroCliente.moveToFront();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        GUIListarClientes escolherCliente = new GUIListarClientes(clientes, fieldNomeCliente);
        escolherCliente.setTitle("Escolha de cliente");
        escolherCliente.setVisible(true);
        escolherCliente.setResizable(true);
        escolherCliente.setMaximizable(true);
        escolherCliente.setClosable(true);
        escolherCliente.setIconifiable(true);
        escolherCliente.setVisible(true);
        escolherCliente.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        this.painelPrincipal.add(escolherCliente);
        escolherCliente.moveToFront();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        GUIConsultarItens addItens = new GUIConsultarItens(itens, jTable1);
        addItens.setTitle("Adicionar Itens");
        addItens.setVisible(true);
        addItens.setResizable(true);
        addItens.setMaximizable(true);
        addItens.setClosable(true);
        addItens.setIconifiable(true);
        addItens.setVisible(true);
        addItens.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        this.painelPrincipal.add(addItens);
        addItens.moveToFront();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
        int linhaSelecionada = jTable1.getSelectedRow();
        dtm.removeRow(linhaSelecionada);
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed

        if (fieldNomeCliente.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Entre com um cliente.");
        } else {
            cliente = new Cliente();
            cliente.setNome(fieldNomeCliente.getText());
            cliente = clientes.buscarPorNome(cliente);
            pedido = new Pedido();
            pedido.setCliente(cliente.getId());
            pedido.setEstado(0);
            pedido.setId(pedidos.listar().size() + 1);
            cliente.setPedidos(pedido.getId());
            Item item;
            for (int x = 0; x < jTable1.getRowCount(); x++) {
                item = new Item();
                item.setNome((String) jTable1.getValueAt(x, 0));
                item.setId(itens.buscarPorNome(item).getId());
                item.setQuantidade((Integer) jTable1.getValueAt(x, 1));
                item.setPedidos(pedido.getId());
                pedido.setItens(item);
            }
            pedidos.salvar(pedido);
            JOptionPane.showMessageDialog(this, "Pedido salvo.\nAcesse os pedidos "
                    + "existente\n no menu pedidos em aberto.");
            this.dispose();
        }
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        float totalNota = 0;
        notaFiscal = new NotaFiscal();
        notaFiscal.setId(notasFiscais.listar().size() + 1);
        if (fieldNomeCliente.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Entre com um cliente.");
        } else if (jTable1.getRowCount() <= 0) {
            JOptionPane.showMessageDialog(this, "Nenhum produto nessa lista!");
        } else {
            if (pedido == null) {
                cliente = new Cliente();
                cliente.setNome(fieldNomeCliente.getText());
                cliente = clientes.buscarPorNome(cliente);
                pedido = new Pedido();
                pedido.setId(pedidos.listar().size() + 1);
                pedido.setCliente(cliente.getId());
                cliente.setPedidos(pedido.getId());
                pedido.setEstado(1);
                
                Item item;
                for (int x = 0; x < jTable1.getRowCount(); x++) {
                    item = new Item();
                    item.setNome((String) jTable1.getValueAt(x, 0));
                    item.setId(itens.buscarPorNome(item).getId());
                    item.setQuantidade((Integer) jTable1.getValueAt(x, 1));
                    pedido.setItens(item);
                }
                pedidos.salvar(pedido);

                for (int x = 0; x < jTable1.getRowCount(); x++) {
                    item = new Item();
                    item.setNome((String) jTable1.getValueAt(x, 0));
                    item = itens.buscarPorNome(item);
                    totalNota += (((Integer) jTable1.getValueAt(x, 1))
                            * item.getPrecoCusto()) * ((item.getMargemLucro() / 100) + 1);
                    item.setQuantidade(item.getQuantidade() - (Integer) jTable1.getValueAt(x, 1));
                }
                notaFiscal.setTotal(totalNota);
                Calendar dataTemp = new GregorianCalendar();
                notaFiscal.setData(dataTemp);
                notaFiscal.setPedido(pedido.getId());
                notasFiscais.salvar(notaFiscal);

                JOptionPane.showMessageDialog(this, "Pedido fechado");
                this.dispose();
            } else {
                fecharPedido();
            }
        }
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_jTable1MouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GUIVendas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GUIVendas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GUIVendas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GUIVendas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField fieldNomeCliente;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel labelCPF;
    // End of variables declaration//GEN-END:variables

    private void fecharPedido() {
        Item item;
        boolean problema = false;
        float totalNota = 0;
        notaFiscal = new NotaFiscal();
        notaFiscal.setId(notasFiscais.listar().size() + 1);

        for (int x = 0; x < jTable1.getRowCount(); x++) {
            item = new Item();
            item.setNome((String) jTable1.getValueAt(x, 0));
            item = itens.buscarPorNome(item);
            if ((Integer) jTable1.getValueAt(x, 1) > item.getQuantidade()) {
                problema = true;
                JOptionPane.showMessageDialog(this, "Não possuimos essa quantidade de \""
                        + item.getNome() + "\"em estoque");
            }
        }
        if (problema == false) {
            for (int x = 0; x < jTable1.getRowCount(); x++) {
                item = new Item();
                item.setNome((String) jTable1.getValueAt(x, 0));
                item = itens.buscarPorNome(item);
                totalNota += (((Integer) jTable1.getValueAt(x, 1))
                        * item.getPrecoCusto()) * ((item.getMargemLucro() / 100) + 1);
                item.setQuantidade(item.getQuantidade() - (Integer) jTable1.getValueAt(x, 1));
            }
            notaFiscal.setTotal(totalNota);
            Calendar dataTemp = new GregorianCalendar();
            notaFiscal.setData(dataTemp);
            notaFiscal.setPedido(pedido.getId());
            notasFiscais.salvar(notaFiscal);
            pedido.setEstado(1);
            JOptionPane.showMessageDialog(this, "Pedido fechado.");
            this.dispose();
        } else {
            JOptionPane.showMessageDialog(this, "Alguns itens não puderam ser comprados!");
        }
    }
}
